<template>
  <a-form-model
    ref="loanData"
    :model="form"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    :hideRequiredMark="true"
  >
    <div class="flex justify-end" v-if="approve != 2">
      <a-button type="primary" v-if="!!form.id && readOnly" @click="readOnly = false" v-action:update>
        修改
      </a-button>
      <a-button v-if="!!form.id && !readOnly" type="primary" @click="updata" v-action:update>
        保存
      </a-button>
    </div>
    <a-row>
      <a-col :span="8">
        <a-form-model-item label="实际贷款本金金额：" prop="principal">
          <m-input-number v-model="form.principal" class="length" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item label="资金成本：" prop="costCapital">
          <m-input-number v-model="form.costCapital" class="length" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item label="总贷款额度：">
          <m-input-number :value="totalLoan" disabled class="length" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="最晚首次放款时间：" prop="firstLoanDate">
          <a-date-picker v-model="form.firstLoanDate" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="审批首次最大放款金额：" prop="firstLoanMaxNum">
          <m-input-number
            v-model="form.firstLoanMaxNum"
            class="length"
            :disabled="readOnly && form.id ? true : false"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="货币：" prop="currency">
          <a-select v-model="form.currency" :disabled="readOnly && form.id ? true : false">
            <a-select-option
              :value="item.value"
              v-for="item in curr"
              :key="item.text"
              :disabled="readOnly && form.id ? true : false"
            >
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="贷款期限：" prop="duration">
          <a-input
            v-model="form.duration"
            @change="form.duration = form.duration.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')"
            :disabled="readOnly && form.id ? true : false"
          >
            <a-select slot="addonAfter" v-model="form.durationUnit" prop="durationUnit">
              <a-select-option
                :value="item.value"
                v-for="item in unit"
                :key="item.text"
                :disabled="readOnly && form.id ? true : false"
              >
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-input>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="利息计算方式：" prop="interestCalcType">
          <a-select v-model="form.interestCalcType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="item.value" v-for="item in interestCalc" :key="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="利息付款方式：" prop="interestPayType">
          <a-select v-model="form.interestPayType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="item.value" v-for="item in interestPay" :key="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="利息利率：" prop="rate">
          <a-input
            v-model="form.rate"
            addon-after="%"
            @change="form.rate = form.rate.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            :disabled="readOnly && form.id ? true : false"
          >
            <a-select
              prop="rateType"
              slot="addonBefore"
              v-model="form.rateType"
              :disabled="readOnly && form.id ? true : false"
            >
              <a-select-option :value="item.value" v-for="item in rateTypes" :key="item.text">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-input>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="分摊统计方式" prop="statisticType">
          <a-select v-model="form.statisticType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="item.value" v-for="item in statisticType" :key="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="贷款限额费付款方式：" prop="limitFeeType">
          <a-select v-model="form.limitFeeType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="2">
              月付
            </a-select-option>
            <a-select-option :value="3">
              每月资本化
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="贷款限额费：" prop="limitFeeRate">
          <m-input v-model="form.limitFeeRate" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="贷款限额费金额：">
          <m-input-number :value="limitFee" disabled class="length" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="贷款限额费计算方式：" prop="limitCalcType">
          <a-select v-model="form.limitCalcType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="item.value" v-for="item in limitCalcType" :key="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="贷款限额费利息计算：" prop="limitType">
          <a-select v-model="form.limitType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="item.value" v-for="item in limitType" :key="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="出借人手续费付款方式：" prop="commissionType">
          <a-select v-model="form.commissionType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="1">
              立即付
            </a-select-option>
            <a-select-option :value="4">
              立即资本化
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="出借人手续费：" prop="commissionRate">
          <m-input v-model="form.commissionRate" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="出借人手续费金额：">
          <m-input-number :value="serviceCharge" disabled class="length" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="其他费用付款方式：" prop="otherFeeType">
          <a-select v-model="form.otherFeeType" :disabled="readOnly && form.id ? true : false">
            <a-select-option :value="item.value" v-for="item in otherType" :key="item.text">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="其他费用：" prop="otherFee">
          <m-input-number v-model="form.otherFee" class="length" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="其他费用说明：" prop="otherFeeInstruction">
          <a-textarea
            v-model="form.otherFeeInstruction"
            class="text"
            :rows="4"
            :disabled="readOnly && form.id ? true : false"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <!-- <a-col :span="12">
        <a-form-model-item label="行政费：" prop="administrativeFeeRate">
          <m-input v-model="form.administrativeFeeRate" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col> -->
      <a-col :span="12">
        <a-form-model-item label="行政费金额：" prop="administrativeFeeRate">
          <m-input-number
            v-model="form.administrativeFeeRate"
            :disabled="readOnly && form.id ? true : false"
            class="length"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="退出费：" prop="exitFeeRate">
          <m-input v-model="form.exitFeeRate" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="退出费金额：">
          <m-input-number :value="exitFee" disabled class="length" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="退出费备注：" prop="exitRemark">
          <m-input-number v-model="form.exitRemark" class="length" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="退出计划：" prop="exitPlan">
          <a-input v-model="form.exitPlan" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="报价利率：">
          <a-input disabled :value="quotationRate" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="全包含利率：">
          <a-input addon-after="%" disabled :value="allInclusiveRate" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="预估利息金额：" prop="predictiveInterest">
          <m-input-number
            v-model="form.predictiveInterest"
            class="length"
            :disabled="readOnly && form.id ? true : false"
          />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="总融资费用：">
          <m-input-number :value="totalFinancing" disabled class="length" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="总费用：" prop="total">
          <m-input-number v-model="form.total" class="length" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="LVR(贷款价值比)：" prop="LVR">
          <m-input v-model="form.LVR" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item label="IRR(内部收益率)：" prop="IRR">
          <m-input v-model="form.IRR" :disabled="readOnly && form.id ? true : false" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item label="LTC(贷款费用比)：">
          <a-input addon-after="%" disabled :value="LTC" />
        </a-form-model-item>
      </a-col>
    </a-row>

    <a-button v-if="!form.id ? true : false" class="space" type="primary" @click="onSubmit">
      下一步
    </a-button>
  </a-form-model>
</template>

<script>
import { curr, unit, interestCalc, interestPay, rateTypes, otherType } from '@/dict'
import { createloanData, getloanData, updateloanDataById, createHistory, getDetailList } from '@/api/common'
import NP from 'number-precision'
import moment from 'moment'
import { commonRule, dateRule } from '@/utils/rules'
export default {
  name: 'Loan',
  data(vm) {
    let exitFeeRateValid = (rule, value, callback) => {
      // console.log(value, vm.form.exitRemark)
      if (!value && !vm.form.exitRemark) {
        return callback(new Error('请填写退出费 或退出费备注'))
      } else {
        callback()
      }
    }
    let exitRemarkValid = (rule, value, callback) => {
      if (!value && !vm.form.exitFeeRate) {
        return callback(new Error('请填写退出费 或退出费备注'))
      } else {
        callback()
      }
    }
    return {
      labelCol: { span: 9 },
      wrapperCol: { span: 12 },
      curr,
      unit,
      interestCalc,
      interestPay,
      rateTypes,
      otherType,
      limitFee1: 1,
      serviceCharge1: 1,
      administrative1: 1,
      exitFee1: 1,
      page: '5',
      // Archive: 0,
      readOnly: true,
      statisticType: [
        { text: '月底不计入', value: 0 },
        { text: '月底计入', value: 1 }
      ],
      limitCalcType: [
        { text: '按月计算', value: 0 },
        { text: '按天计算', value: 1 }
      ],
      limitType: [
        { text: '当天不计算', value: 0 },
        { text: '当天计算', value: 1 }
      ],
      form: {
        principal: '',
        costCapital: '',
        totalLoan: '',
        firstLoanDate: null,
        firstLoanMaxNum: '',
        currency: 'NZD',
        duration: '',
        durationUnit: 2,
        interestCalcType: 1,
        interestPayType: 1,
        rate: '',
        rateType: 3,
        statisticType: 0,
        limitCalcType: 0,
        limitType: 0,
        limitFeeType: 2,
        limitFeeRate: '',
        commissionType: 1,
        commissionRate: '',
        otherFee: '',
        otherFeeType: 1,
        otherFeeInstruction: '',
        administrativeFeeRate: '',
        exitFeeRate: '',
        exitRemark: '',
        predictiveInterest: '',
        exitPlan: '',
        total: '',
        LVR: '',
        IRR: ''
      },
      rules: {
        principal: commonRule,
        costCapital: commonRule,
        firstLoanDate: dateRule,
        firstLoanMaxNum: commonRule,
        currency: commonRule,
        duration: commonRule,
        interestCalcType: commonRule,
        interestPayType: commonRule,
        rate: commonRule,
        statisticType: commonRule,
        limitCalcType: commonRule,
        limitType: commonRule,
        limitFeeType: commonRule,
        limitFeeRate: commonRule,
        commissionType: commonRule,
        commissionRate: commonRule,
        otherFee: commonRule,
        otherFeeType: commonRule,
        otherFeeInstruction: commonRule,
        administrativeFeeRate: commonRule,
        exitFeeRate: [{ validator: exitFeeRateValid, trigger: 'blur' }],
        exitRemark: [{ validator: exitRemarkValid, trigger: 'blur' }],
        predictiveInterest: commonRule,
        exitPlan: commonRule,
        total: commonRule,
        LVR: commonRule,
        IRR: commonRule
      }
    }
  },
  computed: {
    approve() {
      return Number(this.$route.query.approve)
    },
    //总贷款额度
    totalLoan() {
      return NP.plus(this.form.principal || 0, this.form.costCapital || 0)
    },
    // 贷款限额费金额
    limitFee() {
      var a = NP.plus(this.form.principal || 0, this.form.costCapital || 0)
      var b = NP.times(NP.divide(NP.times(a, this.form.limitFeeRate || 0), 100), this.form.duration || 0)
      this.limitFee1 = this.form.durationUnit == 2 ? NP.divide(b, 12) : b
      return this.limitFee1.toFixed(2)
    },
    //手续费金额
    serviceCharge() {
      var a = NP.plus(this.form.principal || 0, this.form.costCapital || 0)
      this.serviceCharge1 = NP.divide(NP.times(a, this.form.commissionRate || 0), 100)
      return this.serviceCharge1.toFixed(2)
    },
    //行政费金额
    // administrative() {
    //   var a = NP.plus(this.form.principal || 0, this.form.costCapital || 0)
    //   this.administrative1 = NP.divide(NP.times(a, this.form.administrativeFeeRate || 0), 100)
    //   return this.administrative1.toFixed(2)
    // },
    //退出费金额
    exitFee() {
      var a = NP.plus(this.form.principal || 0, this.form.costCapital || 0)
      this.exitFee1 = NP.divide(NP.times(a, this.form.exitFeeRate || 0), 100)
      return this.exitFee1.toFixed(2)
    },
    //报价利率
    quotationRate() {
      const b = NP.plus(this.form.commissionRate, this.form.exitFeeRate)
      var a = `${this.form.rate}% +${this.form.limitFeeRate}% +${b}% `
      return a
    },
    //全包含利率
    allInclusiveRate() {
      var a = NP.plus(this.form.rate || 0, this.form.limitFeeRate || 0, this.form.commissionRate || 0)
      return a.toFixed(2)
    },
    //总融资费用
    totalFinancing() {
      var a = NP.plus(
        this.form.predictiveInterest || 0,
        this.limitFee1 || 0,
        this.serviceCharge1 || 0,
        this.exitFee1 || 0
      )
      return a.toFixed(2)
    },
    // LTC
    LTC() {
      if (this.form.total) {
        var a = NP.divide(this.form.principal || 0, this.form.total)
        return a.toFixed(2)
      } else {
        return 0
      }
    }
  },
  watch: {
    form: {
      handler(v) {
        let id = this.$route.query.id
        let _form = Object.assign({}, this.form)
        _form.firstLoanDate = _form?.firstLoanDate?.format('X') || null
        this.$store.commit('form/SAVE_DATA', {
          key: 'business/loanData-' + id,
          value: _form
        })
      },
      deep: true
    }
  },
  mounted() {
    let id = this.$route.query.id
    if (id) {
      this.getData()
    }
    if (!this.form.id) {
      const formStore = this.$store.state.form?.['business/loanData-' + id]
      if (formStore) {
        formStore.firstLoanDate = formStore.firstLoanDate ? moment(formStore.firstLoanDate, 'X') : null
        formStore && Object.assign(this.form, formStore)
      }
    }
  },
  methods: {
    async getData() {
      let id = this.$route.query.id
      // const r = await getDetailList(id)
      // this.Archive = r.result.data.Archive
      const res = await getloanData(id, 1)
      let data = res.result.data
      if (data?.[0]) {
        let _form = Object.assign(data?.[0] || {})
        _form.firstLoanDate = moment(_form.firstLoanDate * 1000)
        _form.exitFeeRate = _form.exitFeeRate ? _form.exitFeeRate : ''
        let newData = {}
        for (let k in this.form) {
          newData[k] = _form[k]
        }
        newData.id = _form.id
        // console.log(_form.firstLoanDate)

        Object.assign(this.form, newData)
        var fee = _form.fee
        fee.forEach(el => {
          if (el.feeType == 1) {
            this.form.limitFeeRate = el.rate
            this.form.limitFeeType = el.feePayType
          }
          if (el.feeType == 2) {
            this.form.commissionRate = el.rate
            this.form.commissionType = el.feePayType
          }
          if (el.feeType == 3) {
            this.form.otherFee = el.amount
            this.form.otherFeeType = el.feePayType
            this.form.otherFeeInstruction = el.instruction
          }
          if (el.feeType == 4) this.form.administrativeFeeRate = el.rate
        })
      }
    },
    onSubmit() {
      let projectId = Number(this.$route.query.id)
      this.$refs.loanData.validate(valid => {
        let form = Object.assign({ projectId }, this.form)
        form.totalLoan = this.totalLoan
        form.IRR = Number(form.IRR)
        form.LVR = Number(form.LVR)
        form.administrativeFeeRate = Number(form.administrativeFeeRate)
        form.commissionRate = Number(form.commissionRate)
        form.duration = Number(form.duration)
        form.limitFeeRate = Number(form.limitFeeRate)
        form.rate = Number(form.rate)
        form.firstLoanDate = Number(form.firstLoanDate.startOf('day').format('X'))
        form.exitFeeRate = form.exitFeeRate ? form.exitFeeRate : 0
        if (valid) {
          createloanData(form)
          this.$store.commit('form/CLEAR', 'business/loanData-' + projectId)
          this.$emit('submit')
        }
      })
    },
    updata() {
      let projectId = Number(this.$route.query.id)
      this.$refs.loanData.validate(async valid => {
        let form = Object.assign({ projectId }, this.form)
        form.totalLoan = this.totalLoan
        form.IRR = Number(form.IRR)
        form.LVR = Number(form.LVR)
        form.administrativeFeeRate = Number(form.administrativeFeeRate)
        form.commissionRate = Number(form.commissionRate)
        form.duration = Number(form.duration)
        form.limitFeeRate = Number(form.limitFeeRate)
        form.rate = Number(form.rate)
        form.firstLoanDate = Number(form.firstLoanDate.startOf('day').format('X'))
        form.exitFeeRate = form.exitFeeRate ? form.exitFeeRate : 0
        if (valid) {
          await updateloanDataById(form)
          const history = {
            recordType: 0,
            tableId: Number(projectId)
          }
          await createHistory(history)
        }
        this.$store.commit('form/CLEAR', 'business/loanData-' + projectId)
      })
      this.readOnly = true
    }
  }
}
</script>
<style lang="css" scoped>
.length {
  width: 200px;
}
.text {
  resize: unset;
  vertical-align: top;
}
.space {
  margin-left: 45%;
}
</style>
